package com.oswift.gpm.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.transaction.annotation.Transactional;

import com.oswift.gpm.dao.SystemDao;
import com.oswift.gpm.entity.MessageBean;
import com.oswift.gpm.entity.PageBean;
import com.oswift.gpm.entity.RelationBean;
import com.oswift.gpm.entity.SystemModuleBean;
import com.oswift.gpm.entity.UserBean;
import com.oswift.gpm.service.ISystemModuleService;
import com.oswift.gpm.utils.Constant;
import com.oswift.gpm.utils.PageCode;
import com.oswift.utils.cache.ResourceManager;
import com.oswift.utils.common.CipherUtil;
import com.oswift.utils.exception.ErrorCode;
import com.oswift.utils.exception.PlatException;

/**
 *
 * 权限管理系统的业务处理类
 *
 * @author zhuou
 * @version C03 2013-6-16
 * @since OSwift GPM V1.0
 */
public class SystemModuleServiceImpl implements ISystemModuleService
{
    /**
     * SystemDao spring注入实例
     */
    private SystemDao systemDao;

    /**
     *
     * 添加系统信息，如果有userId，则同时插入t_gpm_r_usersystem表
     * 将t_gpm_systemmodule和t_gpm_user关联
     *
     * @author zhuou
     * @param bean
     * @param userId
     * @return boolean
     * @throws PlatException
     *             GPM公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean addSystem(SystemModuleBean bean, List<String> userId)
        throws PlatException
    {
        boolean isSuccess = false;
        try
        {
            int sysId = Constant.DEFAULT_SYSID;

            // 获取最大Id+1
            SystemModuleBean top1Bean = systemDao.getTop1Sys();
            if (null != top1Bean)
            {
                sysId = top1Bean.getSystemId() + 1;
            }
            bean.setSystemId(sysId);

            // 加密通信签证
            StringBuilder sb = new StringBuilder();
            sb.append(sysId);
            sb.append(bean.getSecretKey());
            bean.setSigned(CipherUtil.generatePassword(sb.toString()));

            if (userId.size() <= 0)
            {
                isSuccess = systemDao.add(bean) > 0 ? true : false;
            }
            else
            {
                List<RelationBean> list = new ArrayList<RelationBean>();
                isSuccess = systemDao.add(bean) > 0 ? true : false;
                if (isSuccess)
                {
                    for (String id : userId)
                    {
                        RelationBean rBean = new RelationBean();
                        rBean.setAId(sysId);
                        rBean.setMId(Integer.valueOf(id));
                        list.add(rBean);
                    }
                    isSuccess = systemDao.addUserRSys(list) > 0 ? true : false;
                    if (!isSuccess)
                    {
                        // 抛出异常回滚
                        throw new PlatException(ErrorCode.COMMON_DB_ERROR);
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
        return isSuccess;
    }

    /**
     *
     * 获取有分页的系统列表
     *
     * @author zhuou
     * @param pageRecordNum
     * @param pageNum
     * @return PageBean
     * @throws PlatException
     *             平台公共异常
     */
    public PageBean getSysList(int pageRecordNum, int pageNum)
        throws PlatException
    {
        int rowNum = (pageNum - 1) * pageRecordNum;

        Map<String, Object> param = new HashMap<String, Object>();
        param.put("rowNum", rowNum);
        param.put("pageNum", pageRecordNum);

        try
        {
            List<SystemModuleBean> list = systemDao.selectList(param);
            int totalRecordNum = systemDao.selectCount(null);
            PageBean bean = new PageBean();
            bean.setTotalRecordNum(totalRecordNum);
            bean.setDataList(list);
            return bean;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据systemId获取系统详情
     *
     * @author zhuou
     * @param systemId
     * @return SystemModuleBean
     * @throws PlatException
     *             平台公共异常
     */
    public SystemModuleBean getSysDetail(int systemId) throws PlatException
    {
        try
        {
            SystemModuleBean bean = systemDao.selectOne(systemId);
            return bean;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据sysId查询系统下拥有的所有用户
     *
     * @author zhuou
     * @param systemId
     *            系统ID
     * @return List<UserBean>
     */
    public List<UserBean> getUsersBySysId(String systemId) throws PlatException
    {
        try
        {
            List<UserBean> beans = systemDao.getUsersBySysId(systemId);
            return beans;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 修改sys信息
     *
     * @author zhuou
     * @param bean
     *            SystemModuleBean
     * @param userId
     *            用户id字符串
     * @return boolean
     * @throws PlatException
     *             GPM公共异常
     */
    @Transactional(rollbackFor = PlatException.class)
    public boolean updateSystem(SystemModuleBean bean, List<String> userId)
        throws PlatException
    {
        try
        {
            boolean isSuccess = false;

            // 根据sysId删除系统和用户关系表数据
            systemDao.delUserRSysBySysId(bean.getSystemId());

            // 加密通信签证
            StringBuilder sb = new StringBuilder();
            sb.append(bean.getSystemId());
            sb.append(bean.getSecretKey());
            bean.setSigned(CipherUtil.generatePassword(sb.toString()));

            if (userId.size() <= 0)
            {
                isSuccess = systemDao.update(bean) > 0 ? true : false;
            }
            else
            {
                List<RelationBean> list = new ArrayList<RelationBean>();
                isSuccess = systemDao.update(bean) > 0 ? true : false;
                if (isSuccess)
                {
                    for (String id : userId)
                    {
                        RelationBean rBean = new RelationBean();
                        rBean.setAId(bean.getSystemId());
                        rBean.setMId(Integer.valueOf(id));
                        list.add(rBean);
                    }
                    isSuccess = systemDao.addUserRSys(list) > 0 ? true : false;
                    if (!isSuccess)
                    {
                        // 抛出异常回滚
                        throw new PlatException(ErrorCode.COMMON_DB_ERROR);
                    }
                }
            }

            return isSuccess;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    /**
     *
     * 根据sysId删除系统信息
     *
     * @author zhuou
     * @param systemId
     *            系统Id
     * @return MessageBean
     * @throws PlatException
     *             GPM公共异常
     */
    public MessageBean delSys(String systemId) throws PlatException
    {
        try
        {
            MessageBean messBean = new MessageBean();
            StringBuilder messInfo = new StringBuilder();

            int rows1 = systemDao.countUsersBySysId(systemId);
            if (rows1 > 0)
            {
                messInfo.append(ResourceManager
                        .getValue(PageCode.SYS_R_USER_EXIST)
                        + Constant.TXT_LINEBREAK);
            }

            int rows2 = systemDao.countRolesBySysId(systemId);
            if (rows2 > 0)
            {
                messInfo.append(ResourceManager
                        .getValue(PageCode.SYS_R_ROLE_EXIST)
                        + Constant.TXT_LINEBREAK);
            }

            int rows3 = systemDao.countGroupsBySysId(systemId);
            if (rows3 > 0)
            {
                messInfo.append(ResourceManager
                        .getValue(PageCode.SYS_R_GROUP_EXIST)
                        + Constant.TXT_LINEBREAK);
            }

            int rows4 = systemDao.countOpsBySysId(systemId);
            if (rows4 > 0)
            {
                messInfo.append(ResourceManager
                        .getValue(PageCode.SYS_R_OPS_EXIST)
                        + Constant.TXT_LINEBREAK);
            }

            if (rows1 > 0 || rows2 > 0 || rows3 > 0 || rows4 > 0)
            {
                messBean.setCode(PageCode.SYS_DEL_FAIL);
                messBean.setContent(messInfo.toString());
            }
            else
            {
                SystemModuleBean sysBean = systemDao.selectOne(systemId);
                if (null == sysBean)
                {
                    messBean.setCode(PageCode.SYS_ALREADY_DELETE);
                    messBean.setContent(ResourceManager
                            .getValue(PageCode.SYS_ALREADY_DELETE));
                }
                else
                {
                    int rows = systemDao.delete(systemId);
                    if (rows > 0)
                    {
                        messBean.setCode(PageCode.COMMON_SUCCESS);
                        messBean.setContent(ResourceManager
                                .getValue(PageCode.SYS_DEL_SUCCESS));
                    }
                    else
                    {
                        messBean.setCode(PageCode.SYS_DEL_FAIL);
                        messBean.setContent(ResourceManager
                                .getValue(PageCode.SYS_DEL_FAIL));
                    }
                }
            }

            return messBean;
        }
        catch (Exception e)
        {
            throw new PlatException(ErrorCode.COMMON_DB_ERROR, e);
        }
    }

    public SystemDao getSystemDao()
    {
        return systemDao;
    }

    public void setSystemDao(SystemDao systemDao)
    {
        this.systemDao = systemDao;
    }
}
